<?php

function mkdir_recursive($pathname, $mode=0777)
{
    is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname), $mode);
    return is_dir($pathname) || @mkdir($pathname, $mode);
}


function saveForDesign(&$page) {
	//global $html;

	$dirSave = DIR_WWW."DesignSave".DIR_SEP;
	$dirTmp = "page";  //$page->title()."-".date()
	if(!is_dir($dirSave.$dirTmp)) {
		mkdir($dirSave.$dirTmp);
	}
	$baseDir = $dirSave.$dirTmp.DIR_SEP;


	//$html = $page->show();
	$html = $page->bodyContent();
	//echo $html;

	$pattern = '/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'\s>]*)/i';
	$count =  preg_match_all($pattern, $html, $matches);
	//echo $page->show();

	//echo $count;
	for($i=0; $i<$count; $i++) {
		//echo $matches[1][$i]."<br />";
		$file = $matches[1][$i];
		$file = str_replace('/', DIR_SEP, $file);
		$dir = dirname($file);
		$bFile = basename($file);
		$bDir = $baseDir.$dir;
		//$bDir = str_replace('/', DIR_SEP, $bDir);

		if(!is_dir($baseDir.$dir)) {
			//mkdir($bDir, TRUE);
			mkdir_recursive($bDir);
			
		}
		//echo $bDir."<br />";

		$srcFile = DIR_WWW.$file;
		$destFile = $baseDir.$dir.DIR_SEP.$bFile;
		copy($srcFile, $destFile);
	}


	$styles = $page->styles();

	for($i=0; $i<count($styles); $i++) {
		
		$file = $styles[$i];
		$file = str_replace('/', DIR_SEP, $file);
		$dir = dirname($file);
		$bFile = basename($file);
		$bDir = $baseDir.$dir;
		//$bDir = str_replace('/', DIR_SEP, $bDir);

		if(!is_dir($baseDir.$dir)) {
			//mkdir($bDir, TRUE);
			mkdir_recursive($bDir);
			
		}
		//echo $bDir."<br />";

		$srcFile = DIR_WWW.$file;
		$destFile = $baseDir.$dir.DIR_SEP.$bFile;
		copy($srcFile, $destFile);
	}

	$scripts = $page->scripts();

	for($i=0; $i<count($scripts); $i++) {
		$file = $scripts[$i];
		$file = str_replace('/', DIR_SEP, $file);
		$dir = dirname($file);
		$bFile = basename($file);
		$bDir = $baseDir.$dir;
		//$bDir = str_replace('/', DIR_SEP, $bDir);

		if(!is_dir($baseDir.$dir)) {
			//mkdir($bDir, TRUE);
			mkdir_recursive($bDir);
			
		}
		//echo $bDir."<br />";

		$srcFile = DIR_WWW.$file;
		$destFile = $baseDir.$dir.DIR_SEP.$bFile;
		copy($srcFile, $destFile);
	}
	

	file_put_contents($baseDir.$page->title().".html", $page->html());
}

?>
